<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 测试页面</title>
    <style>
        .container {
            width: 80%;
            max-width: 500px;
            height: auto;
            padding: 20px;
            background: #e5fd01;
            position: absolute;
            left: 50%;
            top: 10%;
            transform: translateX(-50%);
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .container div {
            margin: 10px 0;
            width: 100%;
        }

        #message {
            background: aliceblue;
            width: 100%;
            min-height: 100px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <div><button onclick="sendMessage()">发送消息</button></div>
    <div><button onclick="closeConnection()">关闭连接</button></div>
    <div><input type="text" id="text"></div>
    <div id="message"></div>
</div>
</body>
<script>
    // WebSocket 连接
    let ws = new WebSocket("ws://localhost:8080/ws/test");

    ws.onopen = function () {
        console.log("连接成功");
    };

    ws.onmessage = function (event) {
        console.log("收到消息", event.data);
        setMessage(event.data);
    };

    ws.onclose = function () {
        console.log("连接关闭");
    };

    ws.onerror = function (event) {
        console.log("连接错误", event);
    };

    // 发送数据
    function sendMessage() {
        if (ws.readyState === WebSocket.OPEN) {
            let message = document.getElementById("text").value;
            ws.send(message);
            console.log("发送数据", message);
            setMessage(message);
            document.getElementById("text").value = ''; // 清空输入框
        } else {
            console.error("WebSocket 连接未打开");
        }
    }

    function setMessage(data) {
        document.getElementById("message").innerText += '\n' + data;
    }

    // 关闭连接
    function closeConnection() {
        ws.close();
    }
</script>
</html>
